package cn.jofei.common.util;

import cn.jofei.common.exception.BootException;

import java.io.*;
import java.net.MalformedURLException;
import java.nio.file.Paths;

/**
 * 类资源加载
 *
 * @author bao
 * @version ngbao v1.0
 * @date 2022/2/25 11:04
 */
public class Resource {

    public static final String CLASS_PATH = "classpath:";

    /**
     * 资源加载为流
     *
     * @param path
     * @return
     */
    public static InputStream loadAsStream(String path) {
        if (path == null || "".equals(path)) {
            throw new BootException("资源路径不能为空");
        }
        try {
            if (path.startsWith(CLASS_PATH)) {
                path = path.substring(CLASS_PATH.length());
                return getClassLoader().getResourceAsStream(path);
            } else {
                return Paths.get(path).toUri().toURL().openStream();
            }
        } catch (FileNotFoundException | MalformedURLException e) {
            return null;
        } catch (IOException e) {
            throw new BootException(e);
        }
    }

    private static ClassLoader getClassLoader() {
        ClassLoader cl = null;
        try {
            cl = Thread.currentThread().getContextClassLoader();
        } catch (Throwable var3) {
        }
        if (cl == null) {
            cl = Resource.class.getClassLoader();
            if (cl == null) {
                try {
                    cl = ClassLoader.getSystemClassLoader();
                } catch (Throwable var2) {
                }
            }
        }
        return cl;
    }

    /**
     * 资源加载为string
     *
     * @param path
     * @return
     */
    public static String readToString(String path) {
        return readToOutputStream(path).toString();
    }

    public static String readToString(File file) {
        return readToOutputStream(file).toString();
    }

    /**
     * 读取为byte[]
     *
     * @param path
     * @return
     */
    public static byte[] readToByte(String path) {
        return readToOutputStream(path).toByteArray();
    }

    public static ByteArrayOutputStream readToOutputStream(String path) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        InputStream inputStream = null;
        try {
            inputStream = loadAsStream(path);
            byte[] buff = new byte[1024 * 8];
            int len = 0;
            if (inputStream != null) {
                while ((len = inputStream.read(buff)) != -1) {
                    outputStream.write(buff, 0, len);
                }
            }
            return outputStream;
        } catch (IOException e) {
            throw new BootException(e);
        } finally {
            Utils.safeClose(inputStream);
            Utils.safeClose(outputStream);
        }
    }

    public static ByteArrayOutputStream readToOutputStream(File file) {
        return readToOutputStream(file.getAbsolutePath());
    }
}
